package com.isoftstone.disk.spring.security;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

@Component
public class GdmtPasswordEncoder implements PasswordEncoder {
    private Logger logger =  LogManager.getLogger(this.getClass().getName());
    @Value("${passwd.key}")
    private String passwdKey;

    @Override
    public String encode(CharSequence rawPassword) {
        if (rawPassword == null) {
            throw new IllegalArgumentException("rawPassword cannot be null");
        }

        String rst = DigestUtils.md5DigestAsHex((rawPassword + passwdKey).getBytes());
        return rst;
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        if (rawPassword == null) {
            throw new IllegalArgumentException("rawPassword cannot be null");
        } else if (encodedPassword != null && encodedPassword.length() != 0) {
            return encodedPassword.equals(encode(rawPassword));
        } else {
            this.logger.warn("Empty encoded password");
            return false;
        }
    }

    public static void main(String[] args) {
        System.out.println(DigestUtils.md5DigestAsHex(("123457" + "abc123456abc").getBytes()));
    }
}


